﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace Qu.SeniorProject.Model
{
    public class StudentRepository
    {
        public static IEnumerable<Student> GetStudentsEligibleToSeniorProject(string searchParam)
        {
            var spDB = new SeniorProjectEntities();

            return spDB.Database.SqlQuery<Student>("GetStudentsEligibleToSeniorProject @searchParam",
                new SqlParameter("searchParam", searchParam)).ToList();
        }

        public static IEnumerable<Student> GetAll()
        {
            var spDB = new SeniorProjectEntities();

            return spDB.Students;
        }

        public static Student Get(string studentID)
        {
            var spDB = new SeniorProjectEntities();

            return spDB.Students.Where(s => s.StudentId == studentID).FirstOrDefault();
        }

        public static string SetMissingUserName()
        {
            var sb = new StringBuilder();

            var spDB = new SeniorProjectEntities();

            var students = spDB.Students.Where(s => string.IsNullOrEmpty(s.UserName));

            foreach (var student in students)
            {
                string loginName = LdapAuthentication.LdapHelper.GetLoginName(ConfigurationManager.AppSettings["LdapUsername"], ConfigurationManager.AppSettings["LdapPassword"], student.GetFullName(), student.StudentId);
                if (!string.IsNullOrEmpty(loginName))
                {
                    student.UserName = loginName;
                    student.Email = string.Format("{0}@qu.edu.qa", loginName);

                    Console.Out.WriteLine(student.FirstName + " " + student.LastName + " - " + student.Email);
                }
                else
                    sb.Append(student.ToString()).AppendLine();
            }
            spDB.SaveChanges();

            return sb.ToString();

        }
    }
}
